package com.palmap.schedule;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.palmap.model.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Objects;

/**
 * @author zhangxinju
 * @since 2020/5/7 5:28 下午
 */
@Component
@Slf4j(topic = "common")
public class TaskDemo {
    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    public static final String TEST_TOPIC = "test";

    public static final String PRICE_TOPIC = "PRICE_TOPIC";

    public static final String CASE_TOPIC = "CASE_TOPIC";

    private static final ObjectMapper MAPPER = new ObjectMapper();

    private final RedisTemplate<String, Object> redisTemplate;

    @Autowired
    public TaskDemo(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Scheduled(cron = "0 * * * * ?")
    public void test() throws Exception {
        User user = new User();
        user.setAge("27");
        user.setGender("男");
        user.setNickname("william");
        user.setPassword("***");
        user.setUsername("新炬");
        user.setCurrentTime(LocalDateTime.now().format(FORMATTER));
        String userJson = MAPPER.writeValueAsString(user);

        log.info("schedule data:{}", userJson);
        Objects.requireNonNull(redisTemplate.getConnectionFactory()).getConnection().publish(PRICE_TOPIC.getBytes(),
            userJson.getBytes());
    }
}
